/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.xiaoniu.forum.web.controller.app;


import com.xiaoniu.forum.form.BaseForm;
import com.xiaoniu.forum.form.PhoneLoginForm;
import com.xiaoniu.forum.form.UsernamePasswordLoginForm;
import com.xiaoniu.forum.renren.common.exception.RRException;
import com.xiaoniu.forum.renren.common.utils.R;
import com.xiaoniu.forum.renren.common.validator.ValidatorUtils;
import com.xiaoniu.forum.common.utils.JwtUtils;
import com.xiaoniu.forum.renren.modules.sys.service.SysCaptchaService;
import com.xiaoniu.forum.service.AppLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * APP登录授权
 *
 * 用户登录成功后，要把token放到请求头中，每次请求头带上token才算是登录
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/app")
@Api("APP登录接口")
public class AppLoginController {
    @Autowired
    private AppLoginService loginService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private SysCaptchaService captchaService;


    /**
     * 登录
     */
    @PostMapping("phoneLogin")
    @ApiOperation("手机号登录")
    public R login(@RequestBody PhoneLoginForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);
        captchaValidate(form);
        //用户登录
        String userId = loginService.phoneLogin(form);
        //生成token
        String token = jwtUtils.generateToken(userId);
        Map<String, Object> result = createResult(token);
        return R.ok(result);
    }

    @PostMapping("usernameLogin")
    @ApiOperation("账号登录")
    public R login(@RequestBody UsernamePasswordLoginForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);
        //captchaValidate(form);
        //用户登录
        String userId = loginService.usernamePasswordLogin(form);
        //生成token
        String token = jwtUtils.generateToken(userId);
        Map<String, Object>
                result = createResult(token);
        return R.ok(result);
    }

    private Map<String, Object> createResult(String token){
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        return map;
    }

    //校验验证码
    private void captchaValidate(BaseForm form){
        boolean flag = captchaService.validate(form.getUuid(), form.getCaptcha());
        if (!flag){
            throw  new RRException("验证码错误");
        }
    }

}
